package p2pdb

import (
	"encoding/json"

	dbm "hundsun.com/hsl/hschain/store/db"
)

//Option db选项
type Option func(*DbHandler)

//DbHandler db句柄
type DbHandler struct {
	db dbm.Database
}

//NewDbHandler db句柄初始化
func NewDbHandler(p2pDb dbm.Database, opts ...Option) *DbHandler {
	d := &DbHandler{}
	d.db = p2pDb
	for _, opt := range opts {
		opt(d)
	}
	return d
}

//GetJSON 获取json格式信息
func (d *DbHandler) GetJSON(k string, v interface{}) error {
	if d.db == nil {
		return nil
	}
	buf := []byte(k)
	peerInfoBuf, err := d.db.Get(buf)
	if err != nil {
		return err
	}
	err = json.Unmarshal(peerInfoBuf, v)
	return err
}

//PutJSON 存入json格式信息
func (d *DbHandler) PutJSON(k string, v interface{}) error {
	if d.db == nil {
		return nil
	}
	buf, err := json.Marshal(v)
	if err != nil {
		return err
	}
	return d.db.Set([]byte(k), buf)
}
